﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GenericLibrary.ExtensionMethods {

    public static class CollectionExtension {

        class CollectionWrapper<T> {

            private List<T> _itemsToRemove;
            private ICollection<T> _collection;
            private static CollectionWrapper<T> _instance = new CollectionWrapper<T>();

            public static CollectionWrapper<T> Instance {
                get {
                    return _instance;
                }
            }

            public void PendingRemove(ICollection<T> collection, T item) {
                if(collection != this._collection) {
                    if(this._itemsToRemove.Count > 0) {
                        throw new Exception();
                    }
                    this._collection = collection;
                }

                this._itemsToRemove.Add(item);
            }

            public void CommitRemove(ICollection<T> collection) {
                if(collection != this._collection) {
                    throw new Exception();
                }

                for(int i = 0; i < this._itemsToRemove.Count; i++) {
                    this._collection.Remove(this._itemsToRemove[i]);
                }

                this._itemsToRemove.Clear();
                this._collection = null;
            }

            private CollectionWrapper() {
                this._itemsToRemove = new List<T>();
            }
        }

        public static void PendingRemove<T>(this ICollection<T> collection, T item) {
            CollectionWrapper<T>.Instance.PendingRemove(collection, item);
        }

        public static void CommitRemove<T>(this ICollection<T> collection) {
            CollectionWrapper<T>.Instance.CommitRemove(collection);
        }
    }
}
